package com.wanmait.wisdom.interceptor;

import com.auth0.jwt.exceptions.JWTVerificationException;

import com.wanmait.wisdom.entity.Admin;
import com.wanmait.wisdom.util.JWTUtils;
import com.wanmait.wisdom.manage.service.ManageAdminService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class  JWTInterceptor implements HandlerInterceptor {
    @Resource
    private ManageAdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //预检请求放行
        if("OPTIONS".equals(request.getMethod())){
            return true;
        }
        //获得token
        String manageToken = request.getHeader("manageToken");
        if(manageToken==null){
            throw new JWTVerificationException("没有携带manageToken");
        }

        //获得签发对象
        Integer id = null;
        try {
            id = Integer.parseInt(JWTUtils.getAudience(manageToken));
        } catch (NumberFormatException e) {
            throw new JWTVerificationException("解析manageToken获得签发对象失败");
        }

        //查询admin
        Admin admin = adminService.findById(id);
        if(admin==null){
            throw new JWTVerificationException("没有查询到用户");
        }
        JWTUtils.verifyToken(manageToken,admin.getAdminPassword());

        request.setAttribute("admin",admin);

        return true;
    }
}
